(*
 * Materialien zu den zentralen Abiturpruefungen
 * im Fach Informatik ab 2012 in Nordrhein-Westfalen.
 *
 * Klasse TStack
 *
 * NW-Arbeitsgruppe:
 * Materialentwicklung zum Zentralabitur im Fach Informatik
 *
 * Version 2010-12-28
 *)

unit mStack;

interface
type
  TNode = class
  private
    content: TObject;
    nextNode: TNode;
    constructor create(pObject: TObject);
    procedure setNext(pNode: TNode);
    function getContent: TObject;
    function next: TNode;
    destructor destroy; override;
  end;

  TStack = class
  private
    topNode: TNode;
  public
    constructor create; virtual;
    function isEmpty: boolean; virtual;
    function top: TObject; virtual;
    procedure pop; virtual;
    procedure push(pObject: TObject); virtual;
    destructor destroy; override;
  end;

implementation

// TNode

constructor TNode.create(pObject: TObject);
begin
  content := pObject;
  nextNode := nil;
end;

procedure TNode.setNext(pNode: TNode);
begin
  nextNode := pNode;
end;

function TNode.next: TNode;
begin
  result := nextNode;
end;

function TNode.getContent: TObject;
begin
  result := content;
end;

destructor TNode.destroy;
begin
  inherited destroy;
end;

// TStack

constructor TStack.create;
begin
  topNode := nil;
end;

function TStack.isEmpty: boolean;
begin
  result := topNode = nil;
end;

procedure TStack.push(pObject: TObject);
var
  tempNode: TNode;
begin
  if pObject <> nil then
  begin
    tempNode := TNode.create(pObject);
    if self.isEmpty then
      topNode := tempNode
    else
    begin
      tempNode.setnext(topNode);
      topNode := tempNode;
    end;
  end;
end;

procedure TStack.pop;
var
  tempNode: TNode;
begin
  if not self.isEmpty then
  begin
    tempNode := topNode;
    topNode := topNode.next;
    tempNode.destroy;
  end;
end;

function TStack.top: TObject;
begin
  if not self.isEmpty then
    result := topNode.getContent
  else
    result := nil;
end;

destructor TStack.destroy;
begin
  while not self.isEmpty do
    self.pop;
  inherited destroy;
end;

end.
